package com.ffcs.cn.action.map.drawing;

import com.supermap.data.DatasetType;
import com.supermap.data.GeoPoint;
import com.supermap.data.Geometry;
import com.supermap.data.Point2D;
import com.supermap.desktop.core.Application;
import com.supermap.desktop.core.Interface.IBaseItem;
import com.supermap.desktop.core.Interface.IFormMap;
import com.supermap.desktop.core.implement.CtrlAction;
import com.supermap.mapping.Layer;
import com.supermap.mapping.Map;
import com.supermap.ui.Action;
import com.supermap.ui.MapControl;

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * 绘制点
 *
  */
public class CtrlActionDrawingPoint extends CtrlAction {

	public CtrlActionDrawingPoint(IBaseItem caller) {
		super(caller);
	}

	@Override
	protected void run() {
		IFormMap formMap = (IFormMap) Application.getActiveApplication().getActiveForm();
		MapControl mapControl = formMap.getMapControl();
		// 获取当前可编辑的图层
		Layer layer = formMap.getMapControl().getActiveEditableLayer();
		// 图层可编辑且数据集类型为点时才可以添加
		if (layer != null && layer.getDataset().getType() == DatasetType.POINT) {
			mapControl.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
			mapControl.removeMouseListener(mouseAdapter);
			mapControl.addMouseListener(mouseAdapter);
			formMap.dontShowPopupMenu();
		}
	}

	/**
	 * 监听鼠标在地图中的点击事件
	 */
	private final MouseAdapter mouseAdapter = new MouseAdapter() {
		@Override
		public void mouseClicked(MouseEvent e) {
			// 点击左键添加对象
			if (e.getButton() == MouseEvent.BUTTON1) {
				IFormMap formMap = (IFormMap) Application.getActiveApplication().getActiveForm();
				// 获取地图窗口的地图对象
				Map map = formMap.getMapControl().getMap();
				// 将鼠标位置的点转换为地图中的坐标点
				Point2D point2D = map.pixelToMap(e.getPoint());
				// 创建一个几何对象
				Geometry geoPoint = new GeoPoint(point2D);
				// 获取当前可编辑图层
				Layer layer = formMap.getMapControl().getActiveEditableLayer();
				if (layer != null && layer.getDataset().getType() == DatasetType.POINT) {
					formMap.getMapControl().doGeometryCreate(geoPoint);
				}
			} else if (e.getButton() == MouseEvent.BUTTON3) {
				// 点击右键完成
				IFormMap formMap = (IFormMap) Application.getActiveApplication().getActiveForm();
				// 删除监听
				formMap.getMapControl().removeMouseListener(mouseAdapter);
				formMap.showPopupMenu();
				// 鼠标状态返回
				formMap.getMapControl().setAction(Action.SELECT2);
			}
		}
	};

	@Override
	public boolean enable() {
		boolean isEnable = false;
		if (Application.getActiveApplication().getActiveForm() instanceof IFormMap) {
			IFormMap formMap = (IFormMap) Application.getActiveApplication().getActiveForm();
			Layer layer = formMap.getMapControl().getActiveEditableLayer();
			if (layer != null && layer.getDataset().getType() == DatasetType.POINT) {
				isEnable = true;
			}
		}
		return isEnable;
	}
}
